package com.region.spring.client;

import com.region.common.adapter.logging.LoggerAdapter;
import com.region.common.adapter.logging.LoggerAdapterFactory;
import com.region.http.client.config.ClientConfig;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;

/**
 * @author liujieyu
 * @date 2024/7/17 17:09
 * @desciption
 */
public class RegionConfigurer implements BeanDefinitionRegistryPostProcessor {

    private final LoggerAdapter logger = LoggerAdapterFactory.getLogger(getClass());

    private String factoryBeanReferenceName;

    private ClientConfig clientConfig;

    private String[] basePackages;

    public void setFactoryBeanReferenceName(String factoryBeanReferenceName) {
        this.factoryBeanReferenceName = factoryBeanReferenceName;
    }

    public void setClientConfig(ClientConfig clientConfig) {
        this.clientConfig = clientConfig;
    }

    public void setBasePackages(String[] basePackages) {
        this.basePackages = basePackages;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        RegionClassPathBeanDefinitionScanner scanner = new RegionClassPathBeanDefinitionScanner(beanDefinitionRegistry);

        scanner.setFactoryBeanReferenceName(factoryBeanReferenceName);
        if (basePackages != null && basePackages.length != 0) {
            scanner.scan(basePackages);
        } else if (clientConfig != null){
            scanner.scan(clientConfig.getBasePackages());
        } else {
            logger.error("Region adapter spring client config not found in the spring context.");
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        // do nothing
    }

}
